package com.xbongbong.sys.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.saas.enums.FeePayStatusEnum;
import com.xbongbong.sys.domain.dao.FeeLogDao;
import com.xbongbong.sys.domain.entity.FeeLogEntity;
import com.xbongbong.sys.model.FeeLogModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @description:
 * @Author: hongxiao
 * @date: 2019-01-14 22:05
 */
@Service("feeLogModel")
public class FeeLogModelImpl implements FeeLogModel {

    @Resource
    private FeeLogDao feeLogDao;

    @Resource
    private PaasRedisHelper paasRedisHelper;

    @Override
    public Integer insert(FeeLogEntity entity){
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        return feeLogDao.insert(entity);
    }

    @Override
    public Integer update(FeeLogEntity entity){
        entity.setUpdateTime((long)DateUtil.getInt());

        return feeLogDao.update(entity);
    }

    @Override
    public Integer save(FeeLogEntity entity){

        if(entity.getId() == null || Objects.equals(0L, entity.getId())) {
            return insert(entity);
        }
        return update(entity);
    }

    @Override
    public Integer deleteByKey(Long key, String corpid){
        return feeLogDao.deleteByKey(key, corpid);
    }

    @Override
    public FeeLogEntity getByKey( Long key, String corpid){
        return feeLogDao.getByKey(key,corpid);
    }

    @Override
    public FeeLogEntity getDingTalkPayInfo(String corpid) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("feeType", 12);
        param.put("start", 0);
        param.put("pageNum", 1);
        param.put("orderByStr", " add_time desc ");
        List<FeeLogEntity> firstFeeLogList = findEntitys(param);
        return firstFeeLogList.size() > 0 ? firstFeeLogList.get(0) : null;
    }

    @Override
    public List<FeeLogEntity> findEntitys(Map<String ,Object> param){
        return feeLogDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String ,Object>  param){
        return feeLogDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    /**
     * 根据支付结果，更新订单信息，outTradeNo之内的套餐会被标记为激活已支付，其他激活未支付的套餐标记为失效
     * 返回 corpid和feeId
     * @param outTradeNo 以中划线隔开的orderId ，如  100-1480750556
     */
    @Override
    public Map<String,Object> updatePayed(String tradeNo,String outTradeNo) {
        Map<String, Object> result = new HashMap<>(16);

        String orderId = outTradeNo;
        // 没有有效参数
        if(null == orderId ){
            return result;
        }
        Map<String, Object> param = new HashMap<>(16);
        param.put("orderId", orderId);

        List<FeeLogEntity> list = findEntitys(param);
        // 没有有效的套餐订单，或者数量不符
        if( list.size() != 1){
            return result;
        }
        FeeLogEntity entity = list.get(0);
        if(entity.getIsPay()!=null&&entity.getIsPay().equals(1)){
            // 防止已支付的订单重复提交。
            return result;
        }

        // 设置为已支付
        entity.setIsPay(FeePayStatusEnum.SUCCESS_PAY.getCode());
        entity.setPayTime((long)DateUtil.getInt());
        entity.setMemo("支付宝支付成功,交易号："+tradeNo);
        update(entity);

        Long feeId=entity.getFeeId();
        String corpid=entity.getCorpid();
        String corpName = entity.getCorpName();
        result.put("feeId", feeId);
        result.put("corpid", corpid);
        result.put("corpName", corpName);
        return result;
    }

    @Override
    public List<FeeLogEntity> getByType(String corpid, int type) {
        return feeLogDao.getByType(corpid, type);
    }

    /**
     * 判断工单是否已过期
     *
     * @param corpid 公司ID
     * @return 否已过期 true -> 过期 false -> 未过期
     * @throws XbbException 异常
     */
    @Override
    public Boolean workOrderV2PastDue(String corpid) throws XbbException {
        String redisKey = corpid + "_" + ValueAddedTypeEnum.WORK_ORDER_V2.getType();
        String value = paasRedisHelper.getValue(RedisPrefixConstant.WORK_ORDER_V2_PAST_DUE, redisKey);
        List<FeeLogEntity> feeLogEntityList;
        if (StringUtil.isNotEmpty(value)) {
            feeLogEntityList = JSONObject.parseArray(value, FeeLogEntity.class);
        } else {
            feeLogEntityList = getByType(corpid, ValueAddedTypeEnum.WORK_ORDER_V2.getType());
            paasRedisHelper.setValue(RedisPrefixConstant.WORK_ORDER_V2_PAST_DUE, redisKey, feeLogEntityList, RedisTimeConstant.LONG_DURATION);
        }
        if (CollectionsUtil.isEmpty(feeLogEntityList)) {
            return true;
        }
        long now = DateTimeUtil.getInt();
        for (FeeLogEntity feeLogEntity : feeLogEntityList) {
            int buyNum = Objects.isNull(feeLogEntity.getBuyNum()) ? 0 : feeLogEntity.getBuyNum();
            if (buyNum > 0 && feeLogEntity.getStartTime() < now && feeLogEntity.getEndTime() > now) {
                return false;
            }
        }
        return true;
    }
}
